package com.wash.shoes.controller.pc;


import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonQueryOrderApi.commonGetOrderStatusV1.CommonOrderStatusRequest;
import com.lop.open.api.sdk.domain.jdcloudprint.RenderService.render4Outer.OutputConfigDTO;
import com.lop.open.api.sdk.domain.jdcloudprint.RenderService.render4Outer.PrintDataDTO;
import com.lop.open.api.sdk.domain.jdcloudprint.RenderService.render4Outer.QueryRenderDTO;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.EcapV1OrdersStatusGetLopRequest;
import com.lop.open.api.sdk.request.jdcloudprint.CloudPrintRenderLopRequest;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersStatusGetLopResponse;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersTraceQueryLopResponse;
import com.lop.open.api.sdk.response.jdcloudprint.CloudPrintRenderLopResponse;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.common.property.JdProperty;
import com.wash.shoes.domain.dto.OrderTransportPageDto;
import com.wash.shoes.domain.jd.JdCreateOrder;
import com.wash.shoes.domain.jd.JdOrderService;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.helper.FactoryAddressHelper;
import com.wash.shoes.oss.AliyunOSSUtil;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.OrderTransportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Collections;
import java.util.UUID;

/**
 * @author ljg
 * @since 2024-09-16
 */
@Log4j2
@Api(tags = {"PC-物流信息"})
@RestController
@RequestMapping({"/orderTransport", "/dev-api/orderTransport"})
public class OrderTransportController {

    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    JdProperty jdProperty;

    @Autowired
    JdCreateOrder jdCreateOrder;

    @Autowired
    OrderService orderService;

    @Autowired
    JdOrderService jdOrderService;

    @Autowired
    private FactoryAddressHelper factoryAddressHelper;


    @ApiOperation("获取列表")
    @PostMapping("/list")
    public R<Page<OrderTransportPo>> pageList(@RequestBody OrderTransportPageDto transportPo) {
        log.info("OrderTransportController pageList {}", JSONObject.toJSONString(transportPo));
        Page<OrderTransportPo> page = orderTransportService.pageList(transportPo);
        return R.ok(page);
    }



    @ApiOperation("取消物流信息")
    @GetMapping("/cancelTransport")
    public R<OrderTransportPo> cancelTransport(String id) {
        log.info("取消物流 {}", id);
        OrderTransportPo orderTransportPo = orderTransportService.getById(id);
        if (orderTransportPo == null) {
            orderTransportPo = orderTransportService.getByWayBillCode(id);
        }

        jdOrderService.cancelJdOrder(orderTransportPo.getWayBillCode());
        return R.ok(orderTransportPo);
    }

    @ApiOperation("获取面单PDF或蓝牙打印指令")
    @GetMapping("/render4Outer")
    public R<String> render4Outer(String wayBillCode) {

        return R.ok(getJdPdfUrl(wayBillCode));
    }


    @ApiOperation("获取面单PDF或蓝牙打印指令")
    @GetMapping("/render4OuterForJPg")
    public R<String> render4OuterForJPg(String wayBillCode) throws IOException {
        String pdfUrl = getJdPdfUrl(wayBillCode);

        URL url = new URL(pdfUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] pdfBytes = byteArrayOutputStream.toByteArray();
            // 加载 PDF 文档
            PDDocument document = PDDocument.load(pdfBytes);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            // 遍历 PDF 的每一页并转换为 JPG 图片,只获取第一页
            BufferedImage bim = pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
            File outputFile = new File(wayBillCode + "_" + UUID.randomUUID() + "-" + (1) + ".jpg");
            ImageIO.write(bim, "jpg", outputFile);
            String urlTemp = AliyunOSSUtil.upload(outputFile, "jdPdf");
            FileUtil.del(outputFile);
            // 关闭文档
            document.close();
            System.out.println("PDF 转换为 JPG 完成！");
            return R.ok(urlTemp);
        } else {
            System.out.println("无法从服务器获取 PDF 文件，响应码: " + responseCode);
            return R.ok("");
        }
    }


    /**
     * 获取pdf地址
     *
     * @param wayBillCode
     * @return 获取pdf地址
     */
    private String getJdPdfUrl(String wayBillCode) {
        CloudPrintRenderLopRequest request = new CloudPrintRenderLopRequest();
        QueryRenderDTO queryRenderDTO = new QueryRenderDTO();
        request.setQueryRenderDTO(queryRenderDTO);
        queryRenderDTO.setCustomerCode(jdProperty.getCustomerCode());
        queryRenderDTO.setTemplateCode("jdkd76x105");
        queryRenderDTO.setOperator("管理员");
        queryRenderDTO.setTaskId(String.valueOf(System.currentTimeMillis()));

        PrintDataDTO printDataDTO = new PrintDataDTO();
        queryRenderDTO.setPrintData(Collections.singletonList(printDataDTO));
        printDataDTO.setOrderNumber(String.valueOf(System.currentTimeMillis()));
        printDataDTO.setCarrierCode("JD");
        printDataDTO.setBillCodeValue(wayBillCode);
        printDataDTO.setBillCodeType("waybillCode");
        printDataDTO.setScene(4);

        OutputConfigDTO outputConfigDTO = new OutputConfigDTO();
        outputConfigDTO.setOutputType(1);
        outputConfigDTO.setDataFormat(1);
        outputConfigDTO.setFileFormat(1);
        queryRenderDTO.setOutputConfig(Collections.singletonList(outputConfigDTO));

        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);

        try {
            CloudPrintRenderLopResponse response = client.execute(request);
            log.info("云打印  request {} ", JSONObject.toJSONString(request));
            log.info("云打印  response {} ", JSONObject.toJSONString(response));
            return response.getPrintResultDTO().getResult().get(0).getUrl();
        } catch (LopException e) {
            log.error(e);
            return e.getErrMsg();
        }
    }


    @ApiOperation("订单状态查询")
    @GetMapping("/commonGetOrderStatusV1")
    public R<Object> commonGetOrderStatusV1(String wayBillCode) {

        OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(wayBillCode);

        EcapV1OrdersStatusGetLopRequest request = new EcapV1OrdersStatusGetLopRequest();
        CommonOrderStatusRequest commonRequest = new CommonOrderStatusRequest();
        request.setRequest(commonRequest);
        commonRequest.setWaybillCode(wayBillCode);
        commonRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
        commonRequest.setCustomerCode(jdProperty.getCustomerCode());

        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);

        try {
            EcapV1OrdersStatusGetLopResponse response = client.execute(request);
            log.info("订单状态  request {} ", JSONObject.toJSONString(request));
            log.info("订单状态  response {} ", JSONObject.toJSONString(response));
            return R.ok(response);
        } catch (LopException e) {
            log.error(e);
            return R.fail(e.getErrMsg());
        }
    }


    @ApiOperation("查询运单全程跟踪")
    @GetMapping("/commonGetOrderTraceV1")
    public R<Object> commonGetOrderTraceV1(String wayBillCode) {

        EcapV1OrdersTraceQueryLopResponse response = jdOrderService.getTransInfo(wayBillCode);
        if (response == null) {
            return R.fail("物流信息获取失败");
        } else {
            return R.ok(response);
        }
    }

    @ApiOperation("jd物流轨迹订阅")
    @GetMapping("/traceSubscribe")
    public R<String> traceSubscribe(String wayBillCode) throws LopException {

        OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(wayBillCode);
        jdCreateOrder.traceSubscribe(orderTransportPo);
        return R.ok("suc");
    }


}

